package com.xu.cloud.common.process.support;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 字节数组HttpInputMessage
 *
 * @author xuguan
 * @since 2025/2/20
 */
public class ByteArrayHttpInputMessage implements HttpInputMessage {
    private static final InputStream EMPTY_STREAM = StreamUtils.emptyInput();
    private final HttpHeaders headers;

    @Nullable
    private final InputStream body;

    public ByteArrayHttpInputMessage(HttpHeaders headers, @Nullable byte[] content) throws IOException {
        this.headers = headers;
        if (!ObjectUtils.isEmpty(content)) {
            this.body = new ByteArrayInputStream(content);
        } else {
            this.body = null;
        }
    }

    @Override
    public HttpHeaders getHeaders() {
        return this.headers;
    }

    @Override
    public InputStream getBody() {
        return this.body != null ? body : EMPTY_STREAM;
    }

    public boolean hasBody() {
        return (this.body != null);
    }
}
